import { defineStore } from 'pinia'
import { getNoopActions, injectState, useRemote, useWorker, wrapSafeActions } from '@/controller/base/index'
import type { Worker } from '@/controller/base/types/worker'
import type { Remote } from '@/controller/base/types/remote'
import type { FridgeFreezerController } from '../FridgeFreezer/definition'
import { createFridgeFreezerState, FridgeFreezerGetters, FridgeFreezerActions } from '../FridgeFreezer/index'
import { DemoBaseActions, createDemoBaseState, setDemoBaseState } from './BaseAppliance'
import { merge } from 'lodash'
import { getDemoProgramActions } from './common/Program'
import type { DemoDatasource } from '@/demo/types'

let demoDatasource!: DemoDatasource

export function useDemoFridgeFreezeControl(): FridgeFreezerController.Control {
  const createDemoFridgeFreezeState: () => FridgeFreezerController.State = () =>
    injectState(
      () => merge(createFridgeFreezerState(), createDemoBaseState()),
      (state) => {
        setDemoBaseState(state, demoDatasource)
      }
    )
  const DemoFridgeFreezerGetters: FridgeFreezerController.Getters = {
    ...FridgeFreezerGetters,
  }
  const DemoFridgeFreezerActions: FridgeFreezerController.Actions = wrapSafeActions<
    FridgeFreezerController.Store,
    FridgeFreezerController.Actions
  >({
    ...merge(getNoopActions(FridgeFreezerActions), DemoBaseActions),
    loadDemoMenuSettings(groupKey: string) {
      this.currentMenuGroupKey = groupKey
      demoDatasource.menuSettings?.map((item, index) => {
        if (item.key == groupKey) {
          this.currentMenuSettings = item.settingValue
          return item
        }
      })
    },
    ...getDemoProgramActions(demoDatasource),
  })
  const useDemoStore = defineStore<
    'DemoFridgeFreezer',
    FridgeFreezerController.State,
    FridgeFreezerController.Getters,
    FridgeFreezerController.Actions
  >('DemoFridgeFreezer', {
    state: createDemoFridgeFreezeState,
    getters: DemoFridgeFreezerGetters,
    actions: DemoFridgeFreezerActions,
  })

  const store = useDemoStore() as FridgeFreezerController.Store
  const worker = useWorker(store) as Worker.ApplianceWorker<FridgeFreezerController.Store>
  const remote = useRemote(store) as Remote.ApplianceRemote<FridgeFreezerController.Store>
  return { store, worker, remote }
}

export function createDemoFridgeFreezerControl(datasource: DemoDatasource): FridgeFreezerController.Control {
  demoDatasource = datasource
  const control = useDemoFridgeFreezeControl()
  return control
}
